<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Notice\Contract\DataServiceInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

class IndexController extends AbstractController
{
    #[Inject]
    protected DataServiceInterface $dataService;

    #[Inject]
    protected Redis $redis;

    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }

    public function testRpc()
    {
        try {
            $result = $this->dataService->getCampuses(['requestId' => uniqid()]);
            return [
                'status' => 'success',
                'data' => $result,
            ];
        } catch (\Throwable $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ];
        }
    }

    public function testDb()
    {
        // Ensure table exists
        Db::statement('CREATE TABLE IF NOT EXISTS ping_test (
            id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            note VARCHAR(64) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;');

        // Insert one row
        $note = 'ok-' . uniqid();
        Db::insert('INSERT INTO ping_test (note) VALUES (?)', [$note]);

        // Query last 5 rows
        $rows = Db::select('SELECT id, note, created_at FROM ping_test ORDER BY id DESC LIMIT 5');

        return [
            'status' => 'success',
            'inserted' => $note,
            'latest' => $rows,
        ];
    }

    public function testRedis()
    {
        $key = 'ping:test:' . uniqid();
        $value = 'pong';
        $this->redis->set($key, $value);
        $ttl = 60;
        $this->redis->expire($key, $ttl);
        $got = $this->redis->get($key);

        return [
            'status' => 'success',
            'key' => $key,
            'value' => $got,
            'ttl' => $this->redis->ttl($key),
        ];
    }
}
